<template>
  <div>
    <div class="flex flex-column open-box justify-between">
      <div class="flex p-10">
        <label>{{ $t('SERVICE_NAME') }}：</label>
        <p class="flex-1">{{ bizData.bizName }}</p>
      </div>
      <!-- 选中端口信息 -->
      <BaseInfo
        :form-data="formData"
        show-type="restore"
        :route-count="routeCount"
        :obtained-count="obtainedCount"
        :route-list="routeList"
        :recommended="recommended"
      />
      <!-- 链路选择 -->
      <div
        class="route-list-info flex-1 p-5 flex overflow-auto"
        style="flex-direction: column"
      >
        <div class="flex-1">
          <el-tabs v-model="activeName" type="card">
            <!-- 备用路由选择 -->
            <el-tab-pane
              :label="$t('SELECT_CONFIGURED_CHANNEL')"
              name="configed"
            >
              <div
                v-for="(item, index) in backChannelList"
                :key="index"
                class="flex justify-start mb-10 mt-10 top-open-link"
                :class="
                  item.channelList.some((i) => i.checked)
                    ? 'topo-open-active'
                    : ''"
                style="flex-direction: column"
                @click="showRouteDetail(item)"
              >
                <el-checkbox :value="item.channelList.some((i) => i.checked)">
                  {{ $t('STANDBY_LINK') + (index + 1) }}
                </el-checkbox>
                <div class="w-100 pr-10">
                  <p>
                    {{ $t('LINK_LOSS') }}：{{
                      item.loss > 990000
                        ? '--'
                        : changeDecimal(item.loss, 3)
                    }}； {{ $t('NODE_NUM') }}：{{ item.segmentList.length - 2 }}
                  </p>
                  <el-link
                    type="primary"
                    :underline="false"
                    class="white-space-normal"
                    @mouseenter.native="mouseEvent(item, 'always')"
                    @mouseleave.native="mouseEvent(item, 'leave')"
                  >
                    {{ $t('INTERMEDIATE_NODE') }}：
                    {{
                      item.segmentList
                        .map((i) => i.startNode.nodeName)
                        .join('-->') +
                        '-->' +
                        item.segmentList[item.segmentList.length - 1].endNode
                          .nodeName
                    }}
                  </el-link>
                </div>
                <p
                  v-if="
                    item.channelList && item.channelList.some((i) => i.checked)
                  "
                  class="font-small"
                >
                  {{ $t('MOVE_FIBER_DESCRIPTION') }}：
                  <span v-html="cutoverDesc(formData.channelData)" />
                </p>
              </div>
            </el-tab-pane>
            <!-- 新推荐路由选择 -->
            <el-tab-pane :label="$t('RECOMMENDER')" name="new">
              <span slot="label">
                <filter-btn
                  ref="filterBtn"
                  :form-data="formData"
                  :recommended="true"
                  @confirm="filterBtnConfirm"
                  @cancel="filterBtnCancel"
                >
                  <div @click="$refs.filterBtn.showPopover()">{{ $t('RECOMMENDER') }}</div>
                </filter-btn>
              </span>
              <el-radio-group
                v-model="routeSort"
                size="mini"
                class="mr-10"
                @change="sortRouteList"
              >
                <el-radio-button label="linkLength">{{
                  $t('SHORT_LENGTH')
                }}</el-radio-button>
                <el-radio-button label="nodeNum">{{
                  $t('LESS_NODE')
                }}</el-radio-button>
              </el-radio-group>
              <div class="flex-1 overflow-auto">
                <div
                  v-for="(item, index) in routeList"
                  :key="index"
                  class="flex justify-start mb-10 mt-10 top-open-link"
                  style="flex-direction: column"
                  :class="
                    item.channelList &&
                      item.channelList.some((i) => i.checked)
                      ? 'topo-open-active'
                      : ''"
                >
                  <el-checkbox
                    :value="
                      item.channelList &&
                        item.channelList.some((i) => i.checked)
                    "
                  >
                    {{ item.original ? '（' + $t('ORIGINAL_LINK') + '）' : '' }}
                    {{ $t('RECOMMENDATION') + (index + 1) }}
                  </el-checkbox>
                  <div class="w-100 pr-10">
                    <p>
                      {{ $t('TOTAL_CABLE_LENGTH') }}：{{
                        changeDecimal(item.linkLength || 0, 3, true)
                      }}km； {{ $t('NODE_NUM') }}：{{ item.nodeNum - 2 }}
                    </p>
                    <el-link
                      type="primary"
                      :underline="false"
                      class="white-space-normal"
                      @click="showRouteDetail(item)"
                      @mouseenter.native="mouseEvent(item, 'always')"
                      @mouseleave.native="mouseEvent(item, 'leave')"
                    >
                      {{ $t('INTERMEDIATE_NODE') }}：
                      {{ getLinkDetail(item) }}
                    </el-link>
                  </div>
                  <p
                    v-if="
                      item.channelList &&
                        item.channelList.some((i) => i.checked)
                    "
                    class="font-small"
                  >
                    {{ $t('MOVE_FIBER_DESCRIPTION') }}：
                    <span v-html="cutoverDesc(formData.channelData)" />
                  </p>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div
        class="
        flex
        flex-wrap
        justify-end p-5 pt-0 pb-0 mb-10"
      >
        <div>
          <otdr-test-btn
            v-if="formData.channelData && formData.channelData.length"
            class="w-10"
            :form-data="{ ...bizData, ...formData }"
            :is-topo="true"
            @taskChange="taskChange"
          />
        </div>
        <div>
          <el-button type="primary" @click="$emit('close')">
            {{ $t('CANCEL') }}
          </el-button>
          <el-button
            v-if="formData.channelData && formData.channelData.length"
            type="primary"
            @click="save"
          >{{ $t('SAVE') }}</el-button>
        </div>
      </div>
      <!-- 通道列表 -->
      <el-dialog
        v-el-drag-dialog="{updataFull, updataDialogWidth}"
        :fullscreen="isfullscreen"
        :title="$t('INTERMEDIATE_NODE')"
        :visible.sync="routeDetailShow"
        :modal="false"
        :width="setDialogWidth('1000px')"
      >
        <channel-list
          ref="channelList"
          :form-data="formData"
          :row-data="showRouteData || {}"
          :show-cutover-list="false"
          :type="activeName === 'configed' ? 'configed' : 'restore'"
          operate-type="restore"
          @configedSelected="configedSelected"
        />
        <span slot="footer">
          <el-button type="primary" @click="closeChannel">{{
            $t('CONFIRM')
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import { mapGetters, mapMutations } from 'vuex'
  import backChannelApi from '@/api/oen/BackChannelApi'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import { deepClone, checkAfs, changeDecimal } from '@/utils/common'
  import ChannelList from '@/components/ChannelList'
  import OtdrTestBtn from '@/components/OtdrTestBtn'
  import FilterBtn from './FilterBtn.vue'
  import BaseInfo from './BaseInfo'
  import mixin from '@/mixin/bizFunctionMixin'

  export default {
    components: {
      ChannelList,
      OtdrTestBtn,
      BaseInfo,
      FilterBtn
    },
    mixins: [mixin],
    props: {
      bizData: {
        type: Object,
        default: () => {}
      }
    },
    inject: ['functionName', 'parentVM'],
    data() {
      return {
        changeDecimal: changeDecimal,
        showRouteData: null,
        activeNames: ['main'],
        routeSort: 'linkLength',
        activeName: 'configed',
        isRecommended: false,
        formData: {
          aPortData: null,
          zPortData: null,
          segmentList: [],
          routeData: null,
          channelData: []
        },
        backChannelList: [],
        bizChannelList: [],
        transTable: {
          // 传输方向NONE("无"),START("A向"),END("Z向"),DUPLEX("双向");
          NONE: 'NONE',
          SEND: 'A',
          RECEIVE: 'Z',
          SEND_RECEIVE: 'DUPLEX'
        },
        routeList: [],
        routeDetailShow: false,
        isOtdrTesting: false // 标识otdr是否在进行中
      }
    },
    computed: {
      ...mapGetters(['baseRegionList'])
    },
    watch: {
      activeName(newVal) {
        this.resetSelected()
      },
      'bizData.bizId': function() {
        this.init()
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      ...mapMutations(['setGisActived']),
      init() {
        this.getBackDetail()
        this.formatBizData()
        this.resetSelected()
        this.activeName = 'configed'
        this.isRecommended = false
      },
      // 链路信息
      getLinkDetail(data) {
        let linkDetail = ''
        data.segmentList.forEach((i) => {
          linkDetail = linkDetail + i.startNode.nodeName + '-->'
          if (i.cable) {
            linkDetail = linkDetail + i.cable.cableName + '-->'
          }
        })
        return linkDetail + data.endNode.nodeName
      },
      // otdr测试状态改变
      taskChange(data) {
        this.isOtdrTesting = data
        this.$store.commit('setIsOtdrTesting', data)
        if (!data) {
          this.showRouteDetail()
        }
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(
          (i) => i.regionId === stationId
        )
        return stationData ? stationData.regionName : ''
      },
      // 拼接业务基本信息
      formatBizData() {
        console.log('this.bizData', this.bizData)
        const channelData = this.bizData.channelList[0]
        const startData = channelData.segmentList[0]
        this.formData.bizId = this.bizData.bizId
        this.formData.aPortData = {
          nodeType: startData.startNode.nodeCategory,
          nodeId: startData.startNodeId,
          nodeName: startData.startNode.nodeName,
          regionId: startData.startNode.stationId,
          regionName: this.getRegionName(startData.startNode.stationId),
          portId: startData.startPortId,
          portName: startData.startPort.bizName,
          interfaceType: 'SINGLE',
          funcType: 'SEND_RECEIVE'
        }
        const endData =
          channelData.segmentList[channelData.segmentList.length - 1]
        this.formData.zPortData = {
          nodeType: endData.endNode.nodeCategory,
          nodeId: endData.endNodeId,
          nodeName: endData.endNode.nodeName,
          regionId: endData.endNode.stationId,
          regionName: this.getRegionName(endData.endNode.stationId),
          portId: endData.endPortId,
          portName: endData.endPort.bizName,
          interfaceType: 'SINGLE',
          funcType: 'SEND_RECEIVE'
        }
        if (this.bizData.channelList[1]) {
          const channelData2 = this.bizData.channelList[1]
          const startData = channelData2.segmentList[0]
          this.formData.aPortData2 = {
            nodeType: startData.startNode.nodeCategory,
            nodeId: startData.startNodeId,
            nodeName: startData.startNode.nodeName,
            regionId: startData.startNode.stationId,
            regionName: this.getRegionName(startData.startNode.stationId),
            portId: startData.startPortId,
            portName: startData.startPort.bizName,
            interfaceType: 'SINGLE',
            funcType: 'SEND_RECEIVE'
          }
          const endData =
            channelData2.segmentList[channelData2.segmentList.length - 1]
          this.formData.zPortData2 = {
            nodeType: endData.endNode.nodeCategory,
            nodeId: endData.endNodeId,
            nodeName: endData.endNode.nodeName,
            regionId: endData.endNode.stationId,
            regionName: this.getRegionName(endData.endNode.stationId),
            portId: endData.endPortId,
            portName: endData.endPort.bizName,
            interfaceType: 'SINGLE',
            funcType: 'SEND_RECEIVE'
          }
        }
        console.log('this.formData', this.formData)
      },
      // 获取备用详情
      getBackDetail() {
        backChannelApi
          .detail({
            bizId: this.bizData.bizId
          })
          .then((res) => {
            if (!res) return
            this.backChannelList = this.formatData(res.backChannelList)
            this.bizChannelList = res.mainChannelList.map(i => i.channelList)
            console.log(this.backChannelList)
          })
      },
      // 拼装组合通道展示数据
      formatData(data) {
        // 拼接组合数据：同链路数据拼接到一条里面
        const newList = []
        data.forEach((i) => {
          // 设置链路唯一linkId 使用通道id拼接保证一定是唯一的
          i.linkId = i.segmentList.map((j) => j.id).join()
          i.checked = false
          const theIndex = newList.findIndex((j) => j.linkId === i.linkId)
          const item = deepClone(i)
          const channelItem = {
            segmentListIds: i.linkId,
            loss: i.loss,
            backId: i.backId,
            exclusive: i.exclusive ? 'EXCLUSIVE' : 'SHARE',
            segmentList: i.channelList
          }
          if (theIndex !== -1) {
            newList[theIndex].channelList.push(channelItem)
          } else {
            item.channelList = [channelItem]
            newList.push(item)
          }
        })
        // 同链路通道拼接完成，设置表单显示信息
        newList.forEach((z) => {
          z.channelList.forEach((i) => {
            i.segmentList.forEach((j, index) => {
              j.startPort.bizName = this.$utils.handleServiceI18n(
                j.startPort.bizName
              )
              j.endPort.bizName = this.$utils.handleServiceI18n(
                j.endPort.bizName
              )
              i['segmentList' + index] = j
            })
          })
        })
        return newList
      },
      showRouteDetail(data) {
        this.showRouteData = data || this.showRouteData
        console.log('this.showRouteData', this.showRouteData)
        if (
          (this.showRouteData.channelList && this.showRouteData.logicMatrix) ||
          this.activeName === 'configed'
        ) {
          this.routeDetailShow = true
        } else {
          this.getChannelList(data, 'restore')
        }
      },
      cutoverDesc(arr) {
        if (arr.some((i) => !Array.isArray(i.cutoverList))) return ''
        const desc = []
        arr.forEach((ele1, index1) => {
          ele1.cutoverList.forEach((ele2, index2) => {
            let str = this.$t('PORT_CONNECT_LINK', {
              msg1: ele2.deviceName,
              msg2: ele2.port.bizName || ele2.port.portName,
              msg3: ele2.connPort.bizName || ele2.connPort.portName
            })
            if (index2 === 0 && arr.length === 2) {
              str = '<br>' + this.$t('CHANNEL') + (index1 + 1) + '：' + str
            }
            desc.push(str)
          })
        })
        return desc.join('；') || this.$t('NO_PIPETTING_IS_REQUIRED')
      },
      resetSelected() {
        // 已配置通道和重新推荐相互切换时，需要重置上次的选择，子组件的formData.channelData里的checked都置为false
        this.formData.routeData &&
          this.formData.channelData.forEach(i => {
            i.checked = false
          })
        this.formData.routeData = null
        this.formData.channelData = []
        this.backChannelList.forEach((i) => {
          i.channelList.forEach((j) => {
            j.checked = false
          })
        })
        this.channelChecked({
          channelData: {
            checked: false
          }
        })
      },
      channelChecked(data) {
        if (this.activeName !== 'configed') {
          this.recommendChannelChecked(data)
        } else {
          this.configedSelected(data)
        }
      },
      // 备用通道选中状态
      configedSelected(data) {
        const checked = data.channelData.checked
        if (checked) {
          const cannotNext = data.channelData.segmentList.some((i, index) => {
            console.log('this.bizChannelList[0]', this.bizChannelList[0])
            return (
              i.status === 'MAIN' &&
              !this.bizChannelList[0].some(j => j.channelId === i.channelId) &&
              !(this.bizChannelList[1] &&
                this.bizChannelList[1].some(j => j.channelId === i.channelId))
            )
          })
          if (cannotNext) {
            data.channelData.checked = false
            this.$message.error(this.$t('BACKUP_OCCUPIED'))
            return
          }
          // 选中状态保存通道和链路信息
          this.formData.selectedType = 'configed'
          data.channelData.checked = checked
          if (this.formData.channelData) {
            this.formData.channelData.push(data.channelData)
          } else {
            this.formData.channelData = [data.channelData]
          }
          this.formData.routeData = { ...data.routeData }
          // 获取割接信息
          if (!data.channelData.cutoverList) { this.getCutoverList(data.channelData) }
        } else {
          if (!this.formData.channelData) return
          // 非选中状态删除已保存通道和链路信息
          this.formData.channelData = this.formData.channelData.filter(
            (i) => i.backId !== data.channelData.backId
          )
          if (this.formData.channelData.length === 0) {
            this.formData.selectedType = ''
            this.formData.routeData = null
          }
        }
      },
      // 获取割接信息
      async getCutoverList(data) {
        const res = await bizOpenApi.cutoverList({
          firstChannel: data.segmentList
        })
        this.$set(this.formData.channelData)
        data.cutoverList = res.firstCutover || []
      },
      // 推荐通道选中状态
      recommendChannelChecked(data) {
        console.log('data', data)
        const checked = data.channelData.checked
        this.formData.channelData &&
          this.formData.channelData.forEach((i) => {
            i.checked = false
          })
        if (checked) {
          // 选中状态保存通道和链路信息
          this.formData.routeData = data.routeData
          this.formData.channelData = data.routeData.channelList.filter(
            (i) => i.channelType === data.channelData.channelType
          )
          this.formData.channelData.forEach((i) => {
            i.checked = checked
          })
        } else {
          // 非选中状态删除已保存通道和链路信息
          this.formData.routeData = null
          this.formData.channelData = []
        }
      },
      async closeChannel() {
        if (
          !this.formData.routeData ||
          !this.formData.channelData ||
          !this.formData.channelData.length
        ) {
          this.$message.error(this.$t('SELECT_RECOVER_CHANNELR'))
          return
        }
        // 双芯判断
        if (this.bizData.channelList.length === 2) {
          const channelData = this.formData.channelData
          // 1.必须两条通道；2.同一链路；3.不同端口
          if (
            channelData.length !== 2 ||
            channelData[0].segmentListIds !== channelData[1].segmentListIds ||
            channelData[0].segmentList[0].startPortId ===
            channelData[1].segmentList[0].startPortId
          ) {
            this.$message.error(this.$t('DOUBLE_NEED_TWO'))
            return
          }
        } else {
          // 单芯只能选一条通道
          if (this.formData.channelData.length > 1) {
            this.$message.error(this.$t('SINGLE_CORE_PORT'))
            return
          }
        }
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'INTELLIGENCE_RECOVERY')
        if (!checkeAfs) return
        this.routeDetailShow = false
      },
      async save() {
        // 判断otdr测试是否正在测试中
        if (this.isOtdrTesting) {
          this.$message.error(this.$t('CONFIRM_RESTORE'))
          return
        }
        if (!this.formData.routeData) {
          this.$message.error(this.$t('SELECT_RECOVER_CHANNELR'))
          return
        }
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'INTELLIGENCE_RECOVERY')
        if (!checkeAfs) return
        // 双芯判断
        if (this.bizData.channelList.length === 2) {
          const channelData = this.formData.channelData
          // 1.必须两条通道；2.同一链路；3.不同端口
          if (
            channelData.length !== 2 ||
            channelData[0].segmentListIds !== channelData[1].segmentListIds ||
            channelData[0].segmentList[0].startPortId ===
            channelData[1].segmentList[0].startPortId
          ) {
            this.$message.error(this.$t('DOUBLE_NEED_TWO'))
            return
          }
        } else {
          // 单芯只能选一条通道
          if (this.formData.channelData.length > 1) {
            this.$message.error(this.$t('SINGLE_CORE_PORT'))
            return
          }
        }
        const formData = deepClone(this.formData)

        const cutoverList = formData.channelData.map((i) => {
          const cutoverData = i.cutoverList.map((j) => {
            return {
              ...j,
              portName: j.port.bizName,
              connPortName: j.connPort.bizName
            }
          })
          return {
            backId: this.activeName === 'configed' ? i.backId : '',
            segmentChannelList: i.segmentList,
            cutoverList: cutoverData
          }
        })
        const queryData = {
          startStationName: this.bizData.startStationName, // 操作日志需要，后端不需要此参数
          bizName: this.bizData.bizName, // 操作日志需要，后端不需要此参数
          functionName: this.parentVM.functionName, // 操作日志需要，后端不需要此参数
          bizId: this.bizData.bizId,
          cutoverList: cutoverList
        }
        bizOpenApi.restore(queryData).then((res) => {
          this.$message.success(this.$t('SAVE_SUCCESS'))
          this.$store.commit('changeTicktack')
          this.$emit('close')
        })
      },
      mouseEvent(data, type) {
        if (data.segmentList && data.segmentList.length) {
          const nodeIds = []
          const cableIds = data.segmentList
            .filter((i) => {
              nodeIds.push(i.startNode.stationId, i.endNode.stationId)
              return i.cableId
            })
            .map((i) => i.cableId)
          if (type === 'always') {
            this.setGisActived({
              cableIds: Array.from(new Set(cableIds)),
              nodeIds: Array.from(new Set(nodeIds)),
              color: 'color-normal'
            })
          } else {
            this.setGisActived({
              cableIds: [],
              nodeIds: [],
              color: ''
            })
          }
        }
      },
      filterBtnCancel() {
        console.log('走这个了')
        this.activeName = 'configed'
      },
      filterBtnConfirm() {
        this.getRouteList('restore')
        this.isRecommended = true
      }
    }
  }
</script>
